package cn.com.blueInfo.autoCode.database;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class AddCommonColumns {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void handle() {
        List<String> tableList = getTableList();
        for (String oneTable : tableList) {
            String dmlSql = getDMLSql(oneTable);
            jdbcTemplate.execute(dmlSql);
        }
    }

    private List<String> getTableList() {
        String queryDatabaseTablesSql = "select table_name from information_schema.`TABLES` " +
                "where TABLE_SCHEMA = 'haiyuan_dev' ";
        List<Map<String, Object>> queryRows = jdbcTemplate.queryForList(queryDatabaseTablesSql);
        List<String> tableList = new ArrayList<>();
        for (Map<String, Object> oneRow : queryRows) {
            for (Map.Entry<String, Object> entry : oneRow.entrySet()) {
                tableList.add(String.valueOf(entry.getValue()));
            }
        }
        return tableList;
    }

    private String getDMLSql(String tableName) {
        return "ALTER TABLE `haiyuan_dev`.`" + tableName + "` " +
                "ADD COLUMN `order_number` int NULL DEFAULT 0 COMMENT '显示排序号（升序排列，值越小越靠前）', " +
                "ADD COLUMN `tenant_id` bigint NOT NULL COMMENT '租户域ID（多租户隔离标识）', " +
                "ADD COLUMN `application_id` bigint NOT NULL COMMENT '所属应用系统ID（关联系统表）', " +
                "ADD COLUMN `remark` varchar(255) NULL COMMENT '操作备注（如更新原因、删除说明）', " +
                "ADD COLUMN `status` tinyint NOT NULL DEFAULT 1 COMMENT '数据状态：1-已启用，2-未启用，3-待定', " +
                "ADD COLUMN `deleted` tinyint NOT NULL DEFAULT 0 COMMENT '删除状态：1-已删除，0-未删除', " +
                "ADD COLUMN `delete_user_id` bigint NULL COMMENT '删除人ID', " +
                "ADD COLUMN `delete_time` datetime NULL COMMENT '删除时间', " +
                "ADD COLUMN `create_user_id` bigint NOT NULL COMMENT '创建人ID', " +
                "ADD COLUMN `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', " +
                "ADD COLUMN `update_user_id` bigint NULL COMMENT '更新人ID', " +
                "ADD COLUMN `update_time` datetime NULL DEFAULT NULL COMMENT '更新时间', " +
                "ADD COLUMN `extend1` varchar(255) NULL COMMENT '扩展字段1（存储简单键值对，如\"key:value\"）', " +
                "ADD COLUMN `extend2` varchar(255) NULL COMMENT '扩展字段2（存储外部系统关联ID，如第三方平台编码）', " +
                "ADD COLUMN `extend3` json NULL COMMENT '扩展字段3（存储复杂结构数据，如动态表单JSON、多语言配置）'; ";
    }

}
